<template>
  <div class="student-task-detail">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <span class="breadcrumb-item">学习任务</span>
      <span class="breadcrumb-separator">/</span>
      <span class="breadcrumb-item current">{{ taskData.title || '任务详情' }}</span>
    </div>

    <!-- 标题区域 -->
    <div class="detail-header">
      <div class="header-left">
        <h1 class="detail-title">{{ taskData.title || '学习任务详情' }}</h1>
        <div class="status-badge" :class="getStatusClass(taskData.status)">
          {{ getStatusText(taskData.status) || '待完成' }}
        </div>
      </div>
      <div class="header-actions">
        <el-button v-if="taskData.status === '待完成'" type="primary" @click="startTask">开始任务</el-button>
        <el-button v-if="taskData.status === '进行中'" type="primary" @click="continueTask">继续任务</el-button>
        <el-button v-if="taskData.status === '已完成'" type="success" disabled>已完成</el-button>
      </div>
    </div>

    <!-- 基本详情区域 -->
    <div class="detail-section">
      <h2 class="section-title">基本详情</h2>
      <div class="detail-content">
        <div class="detail-info">
          <div class="info-row">
            <div class="info-item">
              <span class="info-label">任务名称</span>
              <span class="info-value">{{ taskData.title }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">学科类型</span>
              <span class="info-value">{{ taskData.subject }}</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item">
              <span class="info-label">任务时间</span>
              <span class="info-value">{{ taskData.startTime }} 至 {{ taskData.endTime }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">创建时间</span>
              <span class="info-value">{{ taskData.createTime }}</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item">
              <span class="info-label">任务难度</span>
              <span class="info-value">{{ taskData.difficulty || '中等' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">预计用时</span>
              <span class="info-value">{{ taskData.estimatedTime || '30分钟' }}</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item full-width">
              <span class="info-label">任务描述</span>
              <span class="info-value">{{ taskData.description }}</span>
            </div>
          </div>
        </div>

        <!-- 图片资源展示 -->
        <div class="task-images">
          <h3 class="images-title">任务材料：</h3>
          <div class="images-list">
            <div v-for="(image, index) in taskData.images" :key="index" class="image-file-item">
              <!-- 图片预览区域 -->
              <div class="image-preview-container">
                <div class="file-thumbnail" :class="getFileStatusClass(image.status || 'completed')">
                  <img v-if="image.thumbnail" :src="image.thumbnail" :alt="`任务材料${index + 1}`" class="thumbnail-img" />
                  <div v-else class="file-placeholder">📄</div>
                </div>
              </div>

              <!-- 图片信息区域 -->
              <div class="image-info-container">
                <div class="image-title">{{ image.fileName || `任务材料${index + 1}` }}</div>
                <div class="image-size">{{ image.fileSize || '32.2KB' }}</div>

                <!-- 悬停时显示的描述信息 -->
                <div class="image-description-tooltip">
                  {{ image.description || '暂无描述' }}
                </div>
              </div>

              <!-- 图片操作按钮 -->
              <div class="image-actions">
                <el-button type="primary" link size="small" @click="previewImage(index)">
                  预览
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 学习进度 -->
    <div class="detail-section">
      <h2 class="section-title">学习进度</h2>
      <div class="progress-content">
        <div class="progress-info">
          <div class="progress-item">
            <span class="progress-label">完成进度</span>
            <div class="progress-bar-container">
              <div class="progress-bar">
                <div class="progress-fill" :style="{ width: taskData.progress + '%' }"></div>
              </div>
              <span class="progress-text">{{ taskData.progress }}%</span>
            </div>
          </div>
          <div class="progress-stats">
            <div class="stat-item">
              <span class="stat-value">{{ taskData.completedQuestions || 0 }}</span>
              <span class="stat-label">已完成题目</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ taskData.totalQuestions || 0 }}</span>
              <span class="stat-label">总题目数</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ taskData.score || 0 }}</span>
              <span class="stat-label">当前得分</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 我的作业 -->
    <div class="detail-section">
      <h2 class="section-title">我的作业</h2>
      <div class="homework-section">
        <div v-if="taskData.status === '待完成'" class="homework-empty">
          <div class="empty-icon">📝</div>
          <p class="empty-text">还未开始作业，点击"开始任务"开始学习</p>
        </div>
        <div v-else class="homework-content">
          <div class="homework-item">
            <div class="homework-info">
              <div class="homework-title">作业提交</div>
              <div class="homework-time">提交时间：{{ taskData.submitTime || '未提交' }}</div>
            </div>
            <div class="homework-actions">
              <el-button v-if="taskData.status === '进行中'" type="primary" @click="uploadHomework">
                上传作业
              </el-button>
              <el-button v-if="taskData.status === '已完成'" type="success" @click="viewHomework">
                查看作业
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 错题集 -->
    <div v-if="taskData.status === '已完成'" class="detail-section">
      <div class="section-header">
        <div class="sectionTop-left">
          <h2 class="section-title">我的错题集</h2>
          <div class="error-rate">
            错误率 <span class="error-percentage">{{ taskData.errorRate || '0%' }}</span>
          </div>
        </div>
      </div>
      <div class="error-collection">
        <div v-if="taskData.errorCollection && taskData.errorCollection.length > 0">
          <div v-for="error in taskData.errorCollection" :key="error.id" class="error-item">
            <h3 class="error-title">{{ error.title }}</h3>
            <p class="error-question">{{ error.question }}</p>
            <div class="error-analysis">
              <strong>解析：</strong>{{ error.analysis }}
            </div>
          </div>
        </div>
        <div v-else class="no-errors">
          <div class="no-errors-icon">🎉</div>
          <p>太棒了！这次作业没有错题</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElButton } from 'element-plus'

// 定义接口
interface TaskImage {
  id: string
  thumbnail: string
  fullImage: string
  fileName?: string
  fileSize?: string
  description?: string
  status?: 'uploading' | 'completed' | 'error'
  progress?: number
}

interface ErrorItem {
  id: string
  title: string
  errorCount: number
  question: string
  analysis: string
}

interface StudentTaskData {
  id: string
  title: string
  description: string
  subject: string
  status: string
  startTime: string
  endTime: string
  createTime: string
  difficulty: string
  estimatedTime: string
  progress: number
  completedQuestions: number
  totalQuestions: number
  score: number
  submitTime?: string
  images: TaskImage[]
  errorRate: string
  errorCollection: ErrorItem[]
}

const route = useRoute()
const router = useRouter()
const taskId = ref(route.params.id as string || '')

// 模拟学生任务详情数据
const taskData = ref<StudentTaskData>({
  id: '1',
  title: '数学期中测试',
  description: '二年级数学期中测试，包含口算、应用题和几何题',
  subject: '数学',
  status: '进行中', // 待完成、进行中、已完成
  startTime: '2023-04-23',
  endTime: '2023-05-23',
  createTime: '2023-04-20 14:30',
  difficulty: '中等',
  estimatedTime: '30分钟',
  progress: 65,
  completedQuestions: 13,
  totalQuestions: 20,
  score: 78,
  submitTime: '2023-04-24 16:30',
  images: [
    {
      id: 'img1',
      thumbnail: 'https://via.placeholder.com/80x100?text=Page1',
      fullImage: 'https://via.placeholder.com/800x1000?text=Page1',
      fileName: '数学测试题目.jpg',
      fileSize: '32.2KB',
      description: '数学期中测试题目',
      status: 'completed'
    }
  ],
  errorRate: '15%',
  errorCollection: [
    {
      id: 'err1',
      title: '应用题错误',
      errorCount: 1,
      question: '小明有12个苹果，他送给小红3个，又送给小刚2个，小明还剩几个苹果？',
      analysis: '计算错误，正确答案应该是12-3-2=7个苹果。'
    }
  ]
})

// 获取状态样式类
const getStatusClass = (status: string) => {
  const statusMap: Record<string, string> = {
    '待完成': 'status-pending',
    '进行中': 'status-in-progress',
    '已完成': 'status-completed'
  }
  return statusMap[status] || 'status-pending'
}

// 获取状态文本
const getStatusText = (status: string) => {
  return status
}

// 获取文件状态样式类
const getFileStatusClass = (status: string) => {
  const statusMap: Record<string, string> = {
    'uploading': 'file-uploading',
    'completed': 'file-completed',
    'error': 'file-error'
  }
  return statusMap[status] || 'file-completed'
}

// 开始任务
const startTask = () => {
  ElMessage.success('开始学习任务')
  taskData.value.status = '进行中'
  // 这里可以跳转到学习页面或开始计时
}

// 继续任务
const continueTask = () => {
  ElMessage.info('继续学习任务')
  // 这里可以跳转到学习页面
}

// 上传作业
const uploadHomework = () => {
  ElMessage.info('上传作业')
  // 跳转到拍照页面
  router.push({
    name: 'camera-capture',
    query: {
      context: 'student-homework',
      taskId: taskId.value,
      returnTo: 'student-task-detail'
    }
  })
}

// 查看作业
const viewHomework = () => {
  ElMessage.info('查看已提交的作业')
  // 这里可以显示已提交的作业
}

// 预览图片
const previewImage = (index: number) => {
  ElMessage.info(`预览第${index + 1}张图片`)
  // 这里可以实现图片预览功能
}

// 从数据库加载任务详情
const loadTaskDetail = async () => {
  try {
    const { taskListStorage } = await import('@/utils/taskListDB')
    await taskListStorage.init()

    const task = await taskListStorage.getTaskById(taskId.value)
    if (task) {
      // 更新任务基本信息
      taskData.value.id = task.id
      taskData.value.title = task.title
      taskData.value.description = task.description
      taskData.value.subject = task.subject
      taskData.value.startTime = task.startTime
      taskData.value.endTime = task.endTime
      taskData.value.createTime = task.createdAt

      console.log('学生任务详情已从数据库加载:', task)
    } else {
      console.log('数据库中未找到任务，使用模拟数据')
    }
  } catch (error) {
    console.error('加载任务详情失败:', error)
    console.log('使用模拟数据继续显示任务详情')
  }
}

// 加载任务图片资源
const loadTaskImages = async () => {
  try {
    const { photosStorage } = await import('@/utils/photosDB')
    await photosStorage.init()

    const photos = await photosStorage.getTaskPhotos(taskId.value)
    if (photos && photos.length > 0) {
      const taskImages: TaskImage[] = photos.map((photo, index) => ({
        id: photo.id,
        thumbnail: photo.thumbnail,
        fullImage: photo.fullImage,
        fileName: photo.fileName || `任务材料${index + 1}.jpg`,
        fileSize: photo.fileSize || '32.2KB',
        description: photo.description || '学习任务材料',
        status: 'completed' as const
      }))

      taskData.value.images = taskImages
      console.log('任务图片已加载:', taskImages.length, '张')
    }
  } catch (error) {
    console.error('加载任务图片失败:', error)
  }
}

onMounted(async () => {
  console.log('学生任务详情页加载，任务ID:', taskId.value)

  // 加载任务基本信息
  await loadTaskDetail()

  // 加载任务图片资源
  await loadTaskImages()

  // 检查是否从其他页面跳转过来
  if (route.query.fromHomeworkUpload === 'true') {
    ElMessage.success('作业上传成功')
    taskData.value.status = '已完成'
    taskData.value.progress = 100
  }
})
</script>

<style scoped>
.student-task-detail {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100%;
}

/* 面包屑导航 */
.breadcrumb {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  font-size: 14px;
  color: #666;
}

.breadcrumb-item {
  color: #666;
}

.breadcrumb-item.current {
  color: #303133;
  font-weight: 500;
}

.breadcrumb-separator {
  margin: 0 8px;
  color: #c0c4cc;
}

/* 标题区域 */
.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.detail-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

/* 状态标签 */
.status-badge {
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;
}

.status-pending {
  background: #fdf6ec;
  color: #e6a23c;
  border: 1px solid #f5dab1;
}

.status-in-progress {
  background: #e1f3ff;
  color: #409eff;
  border: 1px solid #b3d8ff;
}

.status-completed {
  background: #f0f9ff;
  color: #67c23a;
  border: 1px solid #c2e7b0;
}

/* 详情区域 */
.detail-section {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.sectionTop-left {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 16px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 16px 0;
}

.error-rate {
  font-size: 14px;
  color: #666;
}

.error-percentage {
  color: #f56c6c;
  font-weight: 600;
}

.detail-content {
  display: flex;
  gap: 24px;
}

.detail-info {
  flex: 1;
}

.info-row {
  display: flex;
  margin-bottom: 16px;
}

.info-item {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.info-item.full-width {
  flex: 2;
}

.info-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.info-value {
  font-size: 14px;
  color: #303133;
}

/* 图片资源展示 */
.task-images {
  width: 300px;
}

.images-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 16px 0;
}

.images-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.image-file-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.image-preview-container {
  flex-shrink: 0;
}

.file-thumbnail {
  width: 60px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  border: 1px solid #dcdfe6;
}

.thumbnail-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.file-placeholder {
  font-size: 24px;
  color: #c0c4cc;
}

.image-info-container {
  flex: 1;
  min-width: 0;
}

.image-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.image-size {
  font-size: 12px;
  color: #909399;
}

.image-actions {
  flex-shrink: 0;
}

/* 学习进度 */
.progress-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.progress-item {
  display: flex;
  align-items: center;
  gap: 16px;
}

.progress-label {
  font-size: 14px;
  color: #606266;
  min-width: 80px;
}

.progress-bar-container {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
}

.progress-bar {
  flex: 1;
  height: 8px;
  background: #f0f2f5;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #409eff 0%, #66b1ff 100%);
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 14px;
  color: #409eff;
  font-weight: 600;
  min-width: 40px;
}

.progress-stats {
  display: flex;
  gap: 32px;
  margin-top: 16px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  display: block;
  font-size: 24px;
  font-weight: 700;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

/* 作业区域 */
.homework-section {
  min-height: 120px;
}

.homework-empty {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 14px;
  margin: 0;
}

.homework-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.homework-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.homework-info {
  flex: 1;
}

.homework-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.homework-time {
  font-size: 12px;
  color: #909399;
}

.homework-actions {
  flex-shrink: 0;
}

/* 错题集 */
.error-collection {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.error-item {
  padding: 16px;
  background: #fef0f0;
  border-radius: 8px;
  border-left: 4px solid #f56c6c;
}

.error-title {
  font-size: 16px;
  font-weight: 600;
  color: #f56c6c;
  margin: 0 0 8px 0;
}

.error-question {
  font-size: 14px;
  color: #303133;
  margin: 0 0 8px 0;
  line-height: 1.5;
}

.error-analysis {
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
}

.no-errors {
  text-align: center;
  padding: 40px 20px;
  color: #67c23a;
}

.no-errors-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .detail-content {
    flex-direction: column;
  }

  .task-images {
    width: 100%;
  }

  .progress-stats {
    gap: 16px;
  }

  .homework-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>
